const fs = require('fs')

function fileToJson(url) {
  return new Promise((resolve, reject) => {
    fs.readFile(url, (err, data) => {
      if (err) {
        console.log(`read file "${url}" faild.`, err)
        reject()
      }

      const strJson = data.toString()
      if (strJson.length) {
        const json = JSON.parse(strJson)
        resolve(json)
      } else {
        console.log('file is empty')
        reject()
      }
    })
  })
}

function jsonToFile(url, str) {
  return new Promise((resolve, reject) => {
    fs.writeFile(url, str, err => {
      if (err) {
        console.log('write file faild')
        reject()
      }
      resolve()
    })
  })
}

function getServerIP() {
  let interfaces = require('os').networkInterfaces()
  for (var devName in interfaces) {
    var iface = interfaces[devName]
    for (var i = 0; i < iface.length; i++) {
      let alias = iface[i]
      if (alias.family === 'IPv4' && alias.address !== '127.0.0.1' && !alias.internal) {
        if (alias.address) {
          return alias.address
        }
      }
    }
  }
}

module.exports = { fileToJson, jsonToFile, getServerIP }
